<template>
  <view class="charts-box">
    <qiun-data-charts
      type="column"
      :opts="opts"
      :chartData="chartData"
	  :ontouch="true"
    />
  </view>
</template>

<script>
//import uCharts from 'u-charts';

export default {
  data() {
    return {
      chartData: {
        categories: [],  // 存放 x 轴时间
        series: []       // 存放柱状图数据
      },
      opts: {
        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
        padding: [15, 15, 0, 5],
		touchMoveLimit: 24,
        enableScroll: true,
        legend: {},
        xAxis: {
          disableGrid: true,
		  scrollShow: true,
          data: []  ,// 动态设置 x 轴数据
		  itemCount:3
        },
        yAxis: {
          data: [{ min: 0 }]
        },
        extra: {
          column: {
            type: "stack",
            width: 30,
            activeBgColor: "#000000",
            activeBgOpacity: 0.08,
            labelPosition: "center"
          }
        }
      }
    };
  },
  created() {
    this.getServerData();
  },
  methods: {
    getServerData() {
      const url = '/api/habit_former/admin/dashboard/finished_plan_user';

      uni.request({
        url: url,
        method: 'GET',
        success: (res) => {
          if (res.data && res.data.code === 200) {
            const data = res.data.data;

            // 处理从服务器获取的数据，设置 x 轴时间和柱状图数据
			let categories = Object.keys(data); 
			let timeStrings = Object.keys(data);  // 获取时间数组作为 x 轴数据
			let sortedDates = timeStrings.map(str => new Date(str)).sort((a, b) => a - b);
			categories = sortedDates.map(date => date.toISOString().slice(0, 10));
			let orderedValues = categories.map(key => data[key]);
			Object.keys(data).forEach((key, index) => {
			    data[key] = orderedValues[index];
			});
			
			console.log(categories)
            let series = [
              {
                name: "当日完成了计划的用户数",
                data: Object.values(data)  // 获取数量作为柱状图数据
              }
            ];

            // 更新图表数据
            this.chartData = {
              categories: categories,
              series: series
            };

            // 更新 opts 中 xAxis 的 data
            this.opts.xAxis.data = categories;
          } else {
            console.error('Failed to fetch data:', res.data); // 输出整个返回数据以便调试
          }
        },
        fail: (err) => {
          console.error('Failed to fetch data:', err);
        },
      });
    }
  }
};
</script>

<style scoped>
.charts-box {
  width: 100%;
  height: 300px;
}
</style>